package com.wujilee.wujileenetty.demos.web.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

/**
 * @author liwuji
 * @date 2024/7/30
 * @desc
 **/
public class FileChannleTest {
    public static void main(String[] args) throws IOException {
//        Test();
//        test1();
//        test2();

    }

    public static  void Test()throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/liwuji/demo.txt");
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("hello wujilee".getBytes());

        byteBuffer.flip();
        channel.write(byteBuffer);
        fileOutputStream.close();
    }
    public  static  void test1() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("/Users/liwuji/demo.txt");
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        channel.read(byteBuffer);
        byteBuffer.flip();
        System.out.println(new String(byteBuffer.array()));
        fileInputStream.close();
    }

    public  static  void test2() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("/Users/liwuji/demo.txt");
        FileChannel channel = fileInputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/liwuji/demo1.txt");
        FileChannel outputStreamChannel = fileOutputStream.getChannel();

        while (true){

            byteBuffer.clear();
            int read = channel.read(byteBuffer);
            if(read == -1){
                break;
            }
            byteBuffer.flip();
            outputStreamChannel.write(byteBuffer);
        }
        fileOutputStream.close();
        fileInputStream.close();

    }
    public  static  void test4() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("/Users/liwuji/demo.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/liwuji/demo1.txt");
        FileChannel channel = fileInputStream.getChannel();
        FileChannel outputStreamChannel = fileOutputStream.getChannel();
        long size = channel.size();
//解决transferTo最大只能传输2g的问题
        for (long  left = channel.size(); left >0 ;) {
            channel.transferTo((size - left), left, outputStreamChannel);
        }
        fileOutputStream.close();
        fileInputStream.close();

    }
}
